import { useEffect, useRef, useState } from 'react';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import {
  tifTypes,
  isSuccess,
  orderStatusTypes,
  getUsdtNum,
  setDefEmployeeId,
  isLocal,
} from '@/utils';
import { historyOrderApi, myHistoryOrderApi, userListApi } from '@/api';
import dayjs from 'dayjs';
import { filterOrder, getYuanGong } from '@/utils/helper';
import { createTimeLie, yuanGongLie } from './ComonOrder';

export default function HistoryEntrustNew() {
  const tableRef: any = useRef('');
  const [yuanGongs, setYuanGongs] = useState<any>([]);
  const [defYuanGongId, setDefYuanGongId] = useState<any>('');

  useEffect(() => {
    initYuanGong();
  }, []);

  // 历史订单
  async function request(e: any) {
    const params = { ...e, userIds: [e.yuanGongId] };
    if (!params.justMyData) delete params.justMyData;
    const res: any = await myHistoryOrderApi(params);
    // console.log('res: 历史订单: ', res);
    console.log('res: 历史订单2: ', res?.data);
    if (!isSuccess(res)) return { data: [], total: 0 };
    // const _list = filterOrder(res?.data, params);
    const _list = res?.data.list;
    return { data: _list, total: res?.data?.total, success: true };
  }

  const columns: any[] = [
    {
      title: '员工',
      dataIndex: 'userName',
      hideInSearch: true,
    },
    yuanGongLie(yuanGongs, defYuanGongId),
    {
      title: '合约',
      dataIndex: 'contract',
      hideInSearch: true,
    },
    {
      title: 'ID',
      dataIndex: 'gateid',
      hideInSearch: true,
    },
    {
      title: '时间',
      dataIndex: 'tstime',
      valueType: 'dateRange',
      hideInTable: true,
      search: { transform: ([startTime, endTime]: any) => ({ startTime, endTime }) },
    },
    // 特殊查询 justMyData
    {
      title: '只看本系统',
      dataIndex: 'justMyData',
      valueType: 'switch',
      hideInTable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'geateCreateTime',
      width: 100,
      render: (text: any) => <>{dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss')}</>,
      hideInSearch: true,
    },
    {
      title: '结束时间',
      dataIndex: 'finish_time',
      width: 100,
      render: (text: any) => <>{dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss')}</>,
      hideInSearch: true,
    },
    {
      title: '方向',
      dataIndex: 'newSize',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <p className={`${+text > 0 ? 'color-red' : 'color-green'}`}>
          {+text > 0 ? '做多' : '做空'}
          {record?.is_liq && '（强平）'}
        </p>
      ),
    },
    {
      title: '成交均价|委托价',
      dataIndex: 'fill_price',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>
          {Number(text).toFixed(2)} <br />
          {record.price === '0' && record.tif === 'ioc' ? '市价' : record.price}
        </>
      ),
    },
    {
      title: '已成交|委托数量',
      dataIndex: 'size',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>
          <div>
            {record?.finish_as === 'cancelled' && 0}
            {record?.finish_as === 'filled' && getUsdtNum(record)}
            &nbsp;USDT
          </div>
          <div>{getUsdtNum(record)}USDT</div>
        </>
      ),
    },
    {
      title: '平仓收益|收益率',
      dataIndex: 'pnl',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>
          {text === '0' ? (
            '--'
          ) : (
            <div className={`${text * record?.userDirection > 0 ? 'color-red' : 'color-green'}`}>
              <div>{Number(text * record?.userDirection)?.toFixed(2)} USDT</div>
              <div>
                {Number(((text * record?.userDirection) / record?.pnl_margin) * 100)?.toFixed(2)}%
              </div>
            </div>
          )}
        </>
      ),
    },
    {
      title: '生效方式',
      dataIndex: 'tif',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>
          {tifTypes[text]} <br />({text.toUpperCase()})
        </>
      ),
    },
    {
      title: '冰山委托(USDT)',
      dataIndex: 'iceberg',
      hideInSearch: true,
      render: (text: any, record: any) => <>{text === 0 ? '-' : getUsdtNum(record, text)}</>,
    },
    {
      title: '只减仓',
      dataIndex: 'is_reduce_only',
      hideInSearch: true,
      render: (text: any) => <>{text ? '是' : '否'}</>,
    },
    {
      title: '止盈/止损',
      dataIndex: 'takeProfitStopLoss',
      hideInSearch: true,
    },
    {
      title: '订单状态',
      dataIndex: 'finish_as',
      render: (text: any) => <>{orderStatusTypes[text]}</>,
      hideInSearch: true,
    },
  ];

  // 员工列表
  const initYuanGong = async () => {
    const yuanGongs: any = await getYuanGong(userListApi);
    setYuanGongs(yuanGongs);
    setDefYuanGongId(setDefEmployeeId(yuanGongs));
  };

  return (
    <>
      {yuanGongs && Object.keys(yuanGongs).length > 0 && (
        <ProTable
          rowKey="id"
          columns={columns}
          request={request}
          actionRef={tableRef}
          options={false}
          scroll={{ x: 1900 }}
          search={{ defaultCollapsed: false }}
          // pagination={false}
        />
      )}
    </>
  );
}
